<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/10
 * Time: 14:58
 */

namespace App\Api\Admin\Controllers;

use App\Exceptions\ApiException;
use Illuminate\Http\Request;
use App\Services\Admin;
use App\Models\ReportType;
use App\Models\Admin\Log;
use App\Models\admin\Info;
use App\Models\Config;
use App\Models\Admin\Role;
use App\Models\AdminUser;
use App\Models\MessagesSent;
use App\Services\MessagesServices;

class SystemController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

    }
    public function index(){
        $data = D('config')->get(['id','tips','value','download_links','ask_value','make_content']);
        return json_success('ok',$data);
    }
    public function modifylink(Request  $request){
        $id = IT('id',true,'请选择ID');
        $app_data = [
          'value' => $request->input('value'),
          'download_links'=>$request->input('download_links'),
          'ask_value'=> $request->input('ask_value'),
          'make_content'=>$request->input('make_content'),
        ];
        $config_data =Config::where('id','=',$id)->first();
        $data = $config_data->update($app_data);
        if($data){
            if($id ==1){
                $system_name= 'Android';
            }else{
                $system_name= 'ios';
            }
            (new Log)->add($this->user, '修改了'.$system_name.'版本最新链接');
            return json_success('ok');
        }else {
            return json_error('修改失败');
        }
    }
    public function about(){
        $about_data = Info::get(['id','content']);
        return json_success('ok',$about_data);
    }
    public  function  UpdateAbout(){
     $id = IT('id',true, '请输入ID');
     $content = IT ('content',true,'请输入你要修改的内容');
     $about_data = Info::where('id','=',$id)->first();
     $data = $about_data->update(['content'=>$content]);
     if($data){
         (new Log)->add($this->user, '修改了公司简介');
         return json_success('ok');
     }else{
         return json_error('修改失败');
     }
    }
    /**
     * 举报栏目列表
     * @return array
     */
    public function Reporttype(){
        $video_type= ReportType::where('type','=',1)->get(['id','name']);
        $people_type= ReportType::where('type','=',2)->get(['id','name']);
        return json_success('ok',['video_type'=>$video_type,'people_type'=> $people_type]);
    }
    /**
     * 添加举报栏目
     * @return array
     * @throws \Exception
     *
     */
    public function addReport(){
        $name = IT('name',true, '请输入栏目名称');
        $type = IT('type',true,'请输入类型');
        $data= [
            'name'=>$name,
            'type'=>intval($type),
            'created_at' => time2date()
        ];
        $select = ReportType::where('name','=',$name)->first();
        if($select){
           return json_error('此栏目已存在');
        }
        if(is_int($type)){
           return json_error('举报的类型，不正确');
        }
        $insert_data=  ReportType::insert($data);
        if($insert_data){
            (new Log)->add($this->user, '添加了举报栏目-'.$name);
            return json_success('ok');
        }else{
            return json_error('添加失败');
        }
    }

    /**
     * 删除举报栏目
     * @return array
     * @throws \Exception
     */
    public function DelReport(){
        $name = IT('name',true, '请输入栏目名称');
        $type = IT('type',true,'请输入类型');
        $select = ReportType::where('name','=',$name)->first();
        if(!$select){
          return  json_error('没有此栏目');
        }
        $del_data = ReportType::where('name','=',$name)->where('type','=',$type)->delete();
        if($del_data){
            (new Log)->add($this->user, '删除了举报栏目名称为-'.$name);
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }
    }

    /**
     * @return array
     * 影片时长
     */
    public function MovieLength(){
        $data = D('movie_length')->first();
        return json_success('ok',$data);
    }
    public function mofifyMlength(){
        $value = IT('content',true,'请输入时长');
       if(!is_numeric($value)){
         return json_error('时间长度必须是数字');
        }
        $data = D('movie_length')->where('id','=',1)->update(['content'=>$value,'updated_at'=>time2date()]);
        if($data){
            (new Log)->add($this->user, '修改了影片时长为-'.$value);
            return json_success('ok');
        }else{
            return json_error('修改失败');
        }
    }

    /**
     * @desc 创建群发短信
     * @return array
     * @throws \Exception
     */
    public function AddGroupSMS()
    {
        $data['title'] = IT('title',true,'请输入标题');
        $data['content'] = IT('content',true,'请输入短信内容');
        $data['user_type'] = IT('user_type',true,'请选择群发对象');
        $this->_CheckSMSData($data);
        $data['status'] = 0;
        $data['operator_id'] = $this->user['id'];
        $data['created_at'] = time2date();
        $data['updated_at'] = time2date();

        $insert_rs = MessagesSent::insert($data);
        if(!$insert_rs){
            return json_error('添加失败');
        }

        (new Log)->add($this->user, '添加了群发短信-'.$data['title']);
        return json_success('ok');
    }

    /**
     * @desc 修改群发短信
     * @return array
     * @throws \Exception
     */
    public function EditGroupSMS()
    {
        $id = IT('id',true,'请选择需要修改的群发短信');
        $data['title'] = IT('title',true,'请输入标题');
        $data['content'] = IT('content',true,'请输入短信内容');
        $data['user_type'] = IT('user_type',true,'请选择群发对象');
        $this->_CheckSMSData($data);
        $data['operator_id'] = $this->user['id'];
        $data['updated_at'] = time2date();
        $rs = MessagesServices::edit_group_sms($id, $data);
        if(!$rs) {
            return json_error('修改群发短信失败');
        }

        (new Log)->add($this->user, '修改群发短信成功-'.$id);
        return json_success('ok');
    }

    /**
     * @desc 开启群发短信
     * @return array
     * @throws \Exception
     */
    public function EditGroupSMSStatus()
    {
        $id = IT('id',true,'请选择需要开启的群发短信');
        $data['status'] = IT('status',true,'状态不能为空');
        $this->_CheckSMSData($data);
        $rs = MessagesServices::edit_group_sms($id, $data);
        if(!$rs) {
            return json_error('开启群发短信失败');
        }

        (new Log)->add($this->user, '开启群发短信成功-'.$id);
        return json_success('ok');

    }

    /**
     * @desc 检测群发消息的数据
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function _CheckSMSData($params)
    {
        $status_arr = [0, 1];
        if(isset($params['status']) && !in_array($params['status'], $status_arr)) {
            EE('群发短信状态异常');
        }

        if(isset($params['title']) && (strlen($params['title']) > 50)) {
            EE('标题的长度不能超过50个字符');
        }

        if(isset($params['content']) && (strlen($params['content']) > 255)) {
            EE('短信内容的长度不能超过50个字符');
        }

        $user_type_arr = [0, 1, 2, 3, 4, 5];
        if(isset($params['user_type']) && !in_array($params['user_type'], $user_type_arr)) {
            EE('群发对象异常');
        }

        return true;
    }

    /**
     * @desc 获取群发短信的列表
     * @param Request $request
     * @return array
     */
    public function GroupSMSList(request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $page_size = (int) $request->input('pageszie');
        $page_size = $page_size ?: 20;
        $offset = ($page - 1) * $page_size;
        $total = MessagesSent::where([])->count();
        $fields = ['id', 'title', 'content', 'status', 'user_type', 'send_succ', 'send_fail', 'operator_id', 'created_at', 'updated_at'];
        $messages_list = MessagesSent::where([])->skip($offset)->take($page_size)->orderBy('id', 'desc')->get($fields);
        $total_page = ceil($total / $page_size);

        return json_success('ok', ['totalpage' => $total_page,'total'=>$total, 'list' => $messages_list,]);
    }

    /**
     * @desc 获取群发短信的对象
     * @return array
     */
    public function GroupSMSUserType()
    {
        return json_success('ok', $this->_SMSUserType());
    }

    public function _SMSUserType()
    {
        $user_type_arr = array(
            [
                'user_type' => 0,
                'msg' => '全部用户',
                'son' => [
                    ['user_type' => 0, 'msg' => '全部']
                ]
            ],
            [
                'user_type' => 1,
                'msg' => '注册用户',
                'son' => [
                    ['user_type' => 1, 'msg' => '全部'],
                    ['user_type' => 3, 'msg' => '普通用户'],
                    ['user_type' => 4, 'msg' => '会员用户'],
                    ['user_type' => 5, 'msg' => '股东用户']
                ]
            ],
            [
                'user_type' => 2,
                'msg' => '通讯录用户',
                'son' => [
                    ['user_type' => 2, 'msg' => '全部']
                ]
            ]
        );

        return $user_type_arr;
    }

    /**
     * @desc 获取群发短信的详情
     * @return array
     */
    public function GroupSMSInfo()
    {
        $id = IT('id',true,'该群发短信不存在');
        $data = MessagesSent::where('id','=',$id)->first();
        if(empty($data)) {
            return json_error('群发短信数据异常');
        }

        $user_type_arr = $this->_SMSUserType();
        $default_user_type = '';
        foreach($user_type_arr as $key => &$user_type) {
            foreach($user_type['son'] as &$type) {
                if($type['user_type'] == $data->user_type) {
                    $default_user_type = $user_type['user_type'].'-'.$type['user_type'];
                }
            }

        }
        $data['default_user_type'] = $default_user_type;

        return json_success('ok', $data);
    }
}